package cn.zcf.pet.controller;

import cn.zcf.basic.utils.JsonResult;

import cn.zcf.basic.utils.PageList;
import cn.zcf.pet.domain.Pet;
import cn.zcf.pet.query.PetQuery;
import cn.zcf.pet.service.IPetService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/pet")
@Api(value = "宠物的API",description="宠物相关的CRUD功能")
public class PetController {
    @Autowired
    private IPetService service;
    @GetMapping
    @ApiOperation(value = "查询全部" )
    public List<Pet> loadAll(){
        return service.loadAll();
    }
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Pet loadById(@PathVariable("id") Long id){
        return service.loadById(id);
    }
    @DeleteMapping("/{id}")
    @ApiOperation(value = "通过ID删除" )
    public JsonResult delete(@PathVariable("id") Long id){
        try {
            service.remove(id);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }
    @PutMapping
    @ApiOperation(value = "新增或修改" )
    public JsonResult addOrUpt(@RequestBody Pet pet){
        try{
            if(pet.getId()==null){
                service.add(pet);
            }
            else {
                service.update(pet);
            }
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("操作失败");
        }
    }
    @PostMapping
    @ApiOperation(value = "分页查询" )
    public PageList<Pet> pageQuery(@RequestBody PetQuery query){
        try {
            return service.pageQuery(query);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageList<Pet>();
        }

    }
    @PatchMapping
    @ApiOperation(value = "批量删除" )
    public JsonResult patchDel(@RequestBody List<Long> ids){
        try {
            service.patchDel(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("删除失败");
        }
    }
    @PostMapping("/onsale")
    public JsonResult onSale(@RequestBody List<Long> ids){
        try {
            service.onSale(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("网络繁忙");
        }
    }
    @PostMapping("/offsale")
    public JsonResult offSale(@RequestBody List<Long> ids){
        try {
            service.offSale(ids);
            return JsonResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.me().setMsg("网络繁忙");
        }
    }
}